<template>
	<view class="container">
		<!-- 顶部操作栏 -->
		<view class="header-section">
			<view class="header-info">
				<text class="header-title">关于我们管理</text>
				<text class="header-subtitle">管理关于我们页面海报</text>
			</view>
			<view class="header-actions">
				<button class="upload-btn" @click="showUploadModal">上传海报</button>
				<button class="preview-btn" @click="previewCurrent">预览</button>
			</view>
		</view>

		<!-- 当前海报 -->
		<view class="current-poster">
			<view class="section-header">
				<text class="section-title">当前海报</text>
				<text class="section-subtitle">学生端显示的关于我们海报</text>
			</view>
			
			<view v-if="currentPoster.imageUrl" class="poster-display">
				<image 
					class="poster-image" 
					:src="getImageUrl(currentPoster.imageUrl)" 
					mode="aspectFit" 
					@click="previewCurrent"
					@error="onImageError"
					@load="onImageLoad"
				></image>
				<view class="poster-info">
					<text class="upload-time">上传时间: {{ formatDateTime(currentPoster.uploadTime) }}</text>
					<text class="image-url">图片URL: {{ currentPoster.imageUrl }}</text>
				</view>
				<view class="poster-actions">
					<button class="action-btn replace-btn" @click="showUploadModal">更换海报</button>
					<button class="action-btn delete-btn" @click="deletePoster">删除海报</button>
				</view>
			</view>
			
			<view v-else class="no-poster">
				<view class="no-poster-icon">🖼️</view>
				<text class="no-poster-title">暂无海报</text>
				<text class="no-poster-desc">点击"上传海报"添加关于我们海报</text>
			</view>
		</view>

		<!-- 客服联系方式 -->
		<view class="contact-section">
			<view class="section-header">
				<text class="section-title">客服联系方式</text>
				<text class="section-subtitle">管理客服联系信息</text>
			</view>
			
			<view class="contact-form">
				<view class="form-item">
					<text class="label">客服电话</text>
					<input 
						class="input" 
						v-model="contactInfo.phone" 
						placeholder="请输入客服电话"
						placeholder-class="placeholder"
						type="number"
					/>
				</view>
				
				<view class="form-item">
					<text class="label">客服微信</text>
					<input 
						class="input" 
						v-model="contactInfo.wechat" 
						placeholder="请输入客服微信号"
						placeholder-class="placeholder"
					/>
				</view>
				
				<view class="form-item">
					<text class="label">客服QQ</text>
					<input 
						class="input" 
						v-model="contactInfo.qq" 
						placeholder="请输入客服QQ号"
						placeholder-class="placeholder"
						type="number"
					/>
				</view>
				
				<button class="save-btn" @click="saveContactInfo">保存联系方式</button>
			</view>
		</view>

		<!-- 上传海报弹窗 -->
		<view class="modal-overlay" v-if="showModal" @click="closeUploadModal">
			<view class="modal-content" @click.stop>
				<view class="modal-header">
					<text class="modal-title">上传海报</text>
					<view class="close-btn" @click="closeUploadModal">
						<text class="close-icon">×</text>
					</view>
				</view>

				<view class="modal-body">
					<view class="upload-section">
						<text class="section-title">关于我们海报</text>
						<view class="upload-area" @click="chooseImage" v-if="!newPoster.imageUrl">
							<text class="upload-icon">📷</text>
							<text class="upload-text">点击选择图片</text>
							<text class="upload-tip">建议尺寸: 适合手机屏幕显示</text>
						</view>
						<view class="image-preview" v-else>
							<image class="preview-image" :src="getImageUrl(newPoster.imageUrl)" mode="aspectFit"></image>
							<view class="image-actions">
								<button class="change-btn" @click="chooseImage">更换图片</button>
							</view>
						</view>
					</view>
				</view>

				<view class="modal-footer">
					<button class="cancel-btn" @click="closeUploadModal">取消</button>
					<button class="submit-btn" @click="submitPoster">确定</button>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
import { API_CONFIG, getApiUrl, getRequestConfig, apiRequest } from '@/config/api.js'

export default {
	data() {
		return {
			loading: false,
			showModal: false,
			currentPoster: {
				imageUrl: '',
				uploadTime: null
			},
			newPoster: {
				imageUrl: ''
			},
			contactInfo: {
				phone: '',
				wechat: '',
				qq: ''
			}
		}
	},
	onLoad() {
		this.loadData()
	},
	methods: {
		async loadData() {
			this.loading = true
			try {
				// 加载关于我们海报数据
				await this.loadAboutUsData()
				// 加载客服联系方式
				await this.loadContactInfo()
			} catch (error) {
				console.error('加载数据失败:', error)
				uni.showToast({
					title: '加载失败',
					icon: 'error'
				})
			} finally {
				this.loading = false
			}
		},
		
		async loadAboutUsData() {
			try {
				const response = await apiRequest({
					url: getApiUrl(API_CONFIG.ENDPOINTS.ABOUT_US),
					...getRequestConfig(uni.getStorageSync('token'))
				})
				
				if (response.data) {
					// 直接使用后端返回的完整URL
					this.currentPoster = {
						imageUrl: response.data.imageUrl || '',
						uploadTime: response.data.updateTime
					}
					console.log('加载的图片URL:', response.data.imageUrl);
				}
			} catch (error) {
				console.error('获取关于我们数据失败:', error)
				// 使用默认数据
				this.currentPoster = {
					imageUrl: '',
					uploadTime: null
				}
			}
		},
		
		async loadContactInfo() {
			try {
				const response = await apiRequest({
					url: getApiUrl(API_CONFIG.ENDPOINTS.CUSTOMER_SERVICE),
					...getRequestConfig(uni.getStorageSync('token'))
				})
				
				if (response.data) {
					this.contactInfo = {
						phone: response.data.phone || '',
						wechat: response.data.wechat || '',
						qq: response.data.qq || ''
					}
				}
			} catch (error) {
				console.error('获取客服信息失败:', error)
				// 使用默认数据
				this.contactInfo = {
					phone: '400-123-4567',
					wechat: 'english_service',
					qq: '123456789'
				}
			}
		},
		
		formatDateTime(date) {
			if (!date) return '暂无'
			const d = new Date(date)
			return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')} ${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`
		},
		
		showUploadModal() {
			this.newPoster.imageUrl = ''
			this.showModal = true
		},
		
		closeUploadModal() {
			this.showModal = false
			this.newPoster.imageUrl = ''
		},
		
		async chooseImage() {
			try {
				const res = await new Promise((resolve, reject) => {
					uni.chooseImage({
						count: 1,
						sizeType: ['compressed'], // 只选择压缩后的图片
						sourceType: ['album', 'camera'],
						success: resolve,
						fail: reject
					})
				})

				// 显示上传进度
				uni.showLoading({
					title: '上传中...'
				})

				// 直接上传图片
				const uploadResult = await this.uploadImage(res.tempFilePaths[0])
				
				// 设置上传后的URL
				this.newPoster.imageUrl = uploadResult.data

				uni.hideLoading()
				uni.showToast({
					title: '图片上传成功',
					icon: 'success'
				})
			} catch (error) {
				uni.hideLoading()
				console.error('选择或上传图片失败:', error)
				uni.showToast({
					title: error.message || '图片处理失败',
					icon: 'none'
				})
			}
		},
		
		async submitPoster() {
			if (!this.newPoster.imageUrl) {
				uni.showToast({
					title: '请选择图片',
					icon: 'none'
				})
				return
			}
			
			uni.showLoading({
				title: '保存中...'
			})
			
			try {
				// 更新关于我们海报
				const aboutUsData = {
					imageUrl: this.newPoster.imageUrl,
					institutionName: '专业辅导班',
					institutionAddress: '北京市海淀区',  
					institutionPhone: '010-12345678',
					institutionEmail: 'contact@tutor.com'
				}
				
				const response = await apiRequest({
					url: getApiUrl(API_CONFIG.ENDPOINTS.ABOUT_US_UPDATE),
					...getRequestConfig(uni.getStorageSync('token'), 'PUT', aboutUsData)
				})
				
				// 更新本地数据
				this.currentPoster = {
					imageUrl: this.newPoster.imageUrl,
					uploadTime: new Date().toISOString()
				}
				
				console.log('设置显示的图片URL:', this.newPoster.imageUrl);
				
				this.closeUploadModal()
				uni.showToast({
					title: '海报保存成功',
					icon: 'success'
				})
			} catch (error) {
				console.error('保存海报失败:', error)
				uni.showToast({
					title: '保存失败: ' + error.message,
					icon: 'error'
				})
			} finally {
				uni.hideLoading()
			}
		},
		
		async uploadImage(imagePath) {
			return new Promise((resolve, reject) => {
				uni.uploadFile({
					url: getApiUrl(API_CONFIG.ENDPOINTS.ABOUT_US_UPLOAD),
					filePath: imagePath,
					name: 'file',
					success: (res) => {
						try {
							console.log('上传响应:', res.data);
							const data = JSON.parse(res.data)
							if (data.code === 200) {
								resolve({
									data: data.data // 图片URL在data字段中
								})
							} else {
								reject(new Error(data.message || '上传失败'))
							}
						} catch (error) {
							console.error('响应解析失败:', error);
							console.error('原始响应:', res.data);
							reject(new Error('响应解析失败: ' + error.message))
						}
					},
					fail: (error) => {
						console.error('上传请求失败:', error);
						reject(error)
					}
				})
			})
		},
		
		previewCurrent() {
			if (this.currentPoster.imageUrl) {
				const imageUrl = this.getImageUrl(this.currentPoster.imageUrl)
				uni.previewImage({
					urls: [imageUrl],
					current: imageUrl
				})
			}
		},
		
		async deletePoster() {
			uni.showModal({
				title: '确认删除',
				content: '确定要删除当前海报吗？',
				success: async (res) => {
					if (res.confirm) {
						try {
							await apiRequest({
								url: getApiUrl(API_CONFIG.ENDPOINTS.ABOUT_US_DELETE),
								...getRequestConfig(uni.getStorageSync('token'), 'DELETE')
							})
							
							this.currentPoster = {
								imageUrl: '',
								uploadTime: null
							}
							
							uni.showToast({
								title: '删除成功',
								icon: 'success'
							})
						} catch (error) {
							console.error('删除海报失败:', error)
							uni.showToast({
								title: '删除失败',
								icon: 'error'
							})
						}
					}
				}
			})
		},
		
		async saveContactInfo() {
			if (!this.contactInfo.phone && !this.contactInfo.wechat && !this.contactInfo.qq) {
				uni.showToast({
					title: '请至少填写一个联系方式',
					icon: 'none'
				})
				return
			}
			
			try {
				await apiRequest({
					url: getApiUrl(API_CONFIG.ENDPOINTS.CUSTOMER_SERVICE_UPDATE),
					...getRequestConfig(uni.getStorageSync('token'), 'POST', this.contactInfo)
				})
				
				uni.showToast({
					title: '保存成功',
					icon: 'success'
				})
			} catch (error) {
				console.error('保存客服信息失败:', error)
				uni.showToast({
					title: '保存失败',
					icon: 'error'
				})
			}
		},

		onImageError(e) {
			console.error('图片加载失败:', e.detail.message);
			uni.showToast({
				title: '图片加载失败',
				icon: 'none'
			});
		},

		onImageLoad(e) {
			console.log('图片加载成功:', e.detail.width, e.detail.height);
		},

		// 获取图片URL，处理临时路径和localhost
		getImageUrl(url) {
			// 如果URL为空或不是字符串，返回空字符串
			if (!url || typeof url !== 'string') {
				return ''
			}
			
			// 检查是否是临时路径
			if (url.includes('tmp/') || url.includes('http://tmp/') || url.includes('__tmp__/')) {
				console.warn('检测到临时路径图片URL:', url)
				return ''
			}
			
			// 如果已经是完整URL，检查是否需要替换localhost
			if (url.startsWith('http://') || url.startsWith('https://')) {
				if (url.includes('localhost:8080')) {
					return url.replace('http://localhost:8080', API_CONFIG.BASE_URL)
				}
				return url
			}
			
			// 如果是相对路径（以/开头），转换为完整的服务器URL
			if (url.startsWith('/')) {
				return `${API_CONFIG.BASE_URL}${url}`
			}
			
			// 其他情况，尝试添加基础URL
			return `${API_CONFIG.BASE_URL}/${url}`
		}
	}
}
</script>

<style lang="scss" scoped>
.container {
	min-height: 100vh;
	background: #0B0F1A;
	padding: 40rpx;
}

.header-section {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 40rpx;
	
	.header-info {
		.header-title {
			display: block;
			font-size: 48rpx;
			color: #FFFFFF;
			font-weight: bold;
			margin-bottom: 8rpx;
		}
		
		.header-subtitle {
			font-size: 28rpx;
			color: #AAB4BE;
		}
	}
	
	.header-actions {
		display: flex;
		gap: 20rpx;
		
		.upload-btn, .preview-btn {
			background: #1a1f2e;
			border: 1rpx solid #2a2f3e;
			color: #FFFFFF;
			font-size: 28rpx;
			padding: 16rpx 24rpx;
			border-radius: 12rpx;
		}
	}
}

.current-poster, .contact-section {
	margin-bottom: 40rpx;
	
	.section-header {
		margin-bottom: 30rpx;
		
		.section-title {
			display: block;
			font-size: 32rpx;
			color: #FFFFFF;
			font-weight: 500;
			margin-bottom: 8rpx;
		}
		
		.section-subtitle {
			font-size: 24rpx;
			color: #AAB4BE;
		}
	}
}

.poster-display {
	background: #1a1f2e;
	border: 1rpx solid #2a2f3e;
	border-radius: 16rpx;
	padding: 30rpx;
	
	.poster-image {
		width: 100%;
		height: 400rpx;
		border-radius: 12rpx;
		margin-bottom: 20rpx;
		background: #2a2f3e;
	}
	
	.poster-info {
		margin-bottom: 20rpx;
		
		.upload-time {
			font-size: 24rpx;
			color: #AAB4BE;
		}

		.image-url {
			font-size: 22rpx;
			color: #AAB4BE;
			margin-top: 8rpx;
		}
	}
	
	.poster-actions {
		display: flex;
		gap: 16rpx;
		
		.action-btn {
			flex: 1;
			padding: 16rpx;
			border-radius: 8rpx;
			font-size: 26rpx;
			border: none;
			
			&.replace-btn {
				background: #1976D2;
				color: #FFFFFF;
			}
			
			&.delete-btn {
				background: #F44336;
				color: #FFFFFF;
			}
		}
	}
}

.no-poster {
	background: #1a1f2e;
	border: 1rpx solid #2a2f3e;
	border-radius: 16rpx;
	padding: 60rpx 30rpx;
	text-align: center;
	
	.no-poster-icon {
		font-size: 80rpx;
		margin-bottom: 20rpx;
	}
	
	.no-poster-title {
		display: block;
		font-size: 32rpx;
		color: #FFFFFF;
		margin-bottom: 12rpx;
	}
	
	.no-poster-desc {
		font-size: 26rpx;
		color: #AAB4BE;
	}
}

.contact-form {
	background: #1a1f2e;
	border: 1rpx solid #2a2f3e;
	border-radius: 16rpx;
	padding: 30rpx;
	
	.form-item {
		margin-bottom: 30rpx;
		
		.label {
			display: block;
			font-size: 28rpx;
			color: #FFFFFF;
			font-weight: 500;
			margin-bottom: 12rpx;
		}
		
		.input {
			width: 100%;
			background: #2a2f3e;
			border: 1rpx solid #3a3f4e;
			border-radius: 8rpx;
			padding: 16rpx;
			font-size: 26rpx;
			color: #FFFFFF;
		}
		
		.placeholder {
			color: #AAB4BE;
		}
	}
	
	.save-btn {
		width: 100%;
		background: #4CAF50;
		color: #FFFFFF;
		border: none;
		border-radius: 8rpx;
		padding: 20rpx;
		font-size: 28rpx;
	}
}

.modal-overlay {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background: rgba(0, 0, 0, 0.8);
	display: flex;
	align-items: center;
	justify-content: center;
	z-index: 1000;
}

.modal-content {
	background: #1a1f2e;
	border: 1rpx solid #2a2f3e;
	border-radius: 16rpx;
	padding: 40rpx;
	margin: 40rpx;
	max-width: 600rpx;
	width: 100%;
	
	.modal-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 30rpx;
		
		.modal-title {
			font-size: 36rpx;
			color: #FFFFFF;
			font-weight: bold;
		}
		
		.close-btn {
			width: 60rpx;
			height: 60rpx;
			border-radius: 50%;
			background: #666;
			display: flex;
			align-items: center;
			justify-content: center;
			
			.close-icon {
				font-size: 32rpx;
				color: #FFFFFF;
			}
		}
	}
	
	.upload-section {
		.section-title {
			display: block;
			font-size: 28rpx;
			color: #FFFFFF;
			font-weight: 500;
			margin-bottom: 20rpx;
		}
		
		.upload-area {
			border: 2rpx dashed #3a3f4e;
			border-radius: 12rpx;
			padding: 60rpx 20rpx;
			text-align: center;
			
			.upload-icon {
				display: block;
				font-size: 60rpx;
				margin-bottom: 16rpx;
			}
			
			.upload-text {
				display: block;
				font-size: 28rpx;
				color: #FFFFFF;
				margin-bottom: 8rpx;
			}
			
			.upload-tip {
				font-size: 22rpx;
				color: #AAB4BE;
			}
		}
		
		.image-preview {
			.preview-image {
				width: 100%;
				height: 300rpx;
				border-radius: 12rpx;
				margin-bottom: 16rpx;
			}
			
			.image-actions {
				text-align: center;
				
				.change-btn {
					background: #1976D2;
					color: #FFFFFF;
					border: none;
					border-radius: 8rpx;
					padding: 12rpx 24rpx;
					font-size: 26rpx;
				}
			}
		}
	}
	
	.modal-footer {
		display: flex;
		gap: 20rpx;
		margin-top: 30rpx;
		
		.cancel-btn, .submit-btn {
			flex: 1;
			padding: 20rpx;
			border-radius: 12rpx;
			font-size: 28rpx;
			border: none;
		}
		
		.cancel-btn {
			background: #666;
			color: #FFFFFF;
		}
		
		.submit-btn {
			background: #1976D2;
			color: #FFFFFF;
		}
	}
}
</style> 